package com.fenghuajueli.module_home;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_pictureselect.PhotoSelectorBuilder;
import com.fenghuajueli.lib_pictureselect.config.PhotoConfig;
import com.fenghuajueli.libbasecoreui.baseswitch.PublicFunction;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV3Helper;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV4Helper;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.data.entity.video.VideoInfoEntity;
import com.fenghuajueli.libbasecoreui.data.entity.video.VideoResponseListEntity;
import com.fenghuajueli.libbasecoreui.listener.BaseCallBackListener;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.AdUtil;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModelFragment2;
import com.fenghuajueli.module_home.databinding.FragmentHomePageBinding;
import com.fenghuajueli.module_home.model.HomePageModel;
import com.fenghuajueli.module_route.HomeModuleRoute;
import com.fenghuajueli.module_route.PlayVideoModuleRoute;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.vip.VipTemplateActivity;
import com.ll.permission.AllowPermissionUseCase;
import com.ll.permission.data.PermissionCase;
import com.ll.permission.data.PermissionParis;
import com.sy.module_ad_switch_manager.AdShowHelper;
import com.sy.module_ad_switch_manager.AdSwitchManger;
import com.sy.module_ad_switch_manager.AdType;

import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;

/**
 * 主页界面
 */
@Route(path = HomeModuleRoute.HOME_PAGE)
public class HomePageFragment extends BaseViewModelFragment2<HomePageModel, FragmentHomePageBinding> {

    private static final String TAG = "HomePageFragment";


    //fragment传递参数示例  kotlin需要加上@JvmField
    @Autowired(name = "name")
    String name;

    @Override
    protected HomePageModel createViewModel() {
        return new HomePageModel();
    }

    @Override
    protected FragmentHomePageBinding createViewBinding() {
        return FragmentHomePageBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView(View containerView) {
        LogUtils.d("接收到的参数：" + name);
        setOnClick();
        V3AdTestActivityKt.initArticleList(binding.articleContainer);
    }

    @Override
    protected void initData() {
        //特惠商品信息 需引入userCore依赖
//        binding.tvSpecialInfo.setOnClickListener(v-> RequestInfoModel.getSpecialGoodsList(this, new TokenErrorBackListener<>() {
//            @Override
//            public void tokenError(int code, String error) {
//
//            }
//
//            @Override
//            public void onSuccess(GoodsData data) {
//                if (!data.getList().isEmpty()) {
//                    binding.tvSpecialInfo.setText("特惠商品信息:" + data.getList().get(0));
//                }
//            }
//
//            @Override
//            public void onFailed(String error) {
//
//            }
//
//            @Override
//            public void onHandlerStart() {
//
//            }
//        }));

        try {
            binding.tvChannelInfo.setText(
                    "当前渠道:" + AppConfigInfo.CHANNEL
                            + "\n包名:" + AppConfigInfo.APPLICATION_ID
                            + "\n付费开关:" + SwitchKeyUtils.getPayStatus()
                            + "\n是否提示升级:" + SwitchKeyUtils.getAppUpdateStatus()
                            + "\n是否提示隐藏指定功能:" + SwitchKeyUtils.getHideFunctionStatus()
                            + "\n广告开关:" + SwitchKeyV4Helper.getAdSwitch()
                            + "\n广告平台:" + getAdPlatform(SwitchKeyV3Helper.getAdType())
                            + "\n付费模板:" + SwitchKeyUtils.getVipTemplateSwitch().getPay_template()
                            + "\n付费卡点开关:" + SwitchKeyUtils.getVipTemplateSwitch().getPay_check_point()
                            + "\n用户token:" + (UserInfoUtils.getInstance().isLogin() ? UserInfoUtils.getInstance().getUserInfoEntity().getToken() : "未登录")
                            + "\n激励模式:开关：" + AdSwitchManger.incentiveMode.getIncentiveModeSwitch() + " 模式名称：" + AdSwitchManger.incentiveMode.getIncentiveModeType().getDesc() + " 免费次数：" + AdSwitchManger.incentiveMode.getIncentiveFreeTimes()
            );
        } catch (Exception e) {
            LogUtils.e("信息异常：" + e);
        }
    }

    private String getAdPlatform(@AdType int adType) {
        String platform = "";
        if (adType == AdType.ADTYPE_CSJ) {
            platform = "穿山甲";
        } else if (adType == AdType.ADTYPE_GM) {
            platform = "Gromore";
        } else if (adType == AdType.ADTYPE_KS) {
            platform = "快手";
        } else if (adType == AdType.ADTYPE_GDT) {
            platform = "优量汇";
        } else if (adType == AdType.ADTYPE_TP) {
            platform = "TopOn";
        }
        return platform;
    }

    private void setOnClick() {
        Intent newintent = new Intent(requireActivity(), V3AdTestActivity.class);
        newintent.setPackage(AppUtils.getAppPackageName());
        binding.tvV3Ad.setOnClickListener(v -> startActivity(newintent));

        binding.tvCamera.setOnClickListener(view -> {
            AllowPermissionUseCase.useCamera(
                    requireActivity(),
                    "相机权限",
                    "用于实现拍摄照片、录制视频进行创作，需要访问您的相机权限，如若拒绝，将无法使用上述功能。",
                    "相机权限：该功能需要相机权限才可以正常运行，用于拍摄照片或录制视频等。",
                    "111",
                    "请开启权限",
                    (Function0<Unit>) () -> {
                        ToastUtils.showShort("已同意相机权限");
                        return null;
                    });
        });
        binding.tvStorageManager.setOnClickListener(view -> {
            AllowPermissionUseCase.useStorageManager(
                    requireActivity(),
                    "外部存储权限",
                    "用于实现文件管理（增、删、改、查），需要访问您的外部存储权限，如若拒绝，将无法使用上述功能。",
                    "外部存储权限：该功能需要外部存储权限才可以正常运行，用于手机文件管理。",
                    "000",
                    "请开启权限",
                    (Function0<Unit>) () -> {
                        ToastUtils.showShort("已同意外部存储权限");
                        return null;
                    });
        });

        binding.tvGallery.setOnClickListener(view -> {
            AllowPermissionUseCase.useGalleryImages(
                    requireActivity(),
                    "相册权限",
                    "用于实现照片制作，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                    "相册权限：该功能需要相册权限才可以正常运行，用于照片制作。",
                    "222",
                    "请开启权限",
                    (Function0<Unit>) () -> {
                        ToastUtils.showShort("已同意相册权限");
                        return null;
                    });
        });

        binding.tvLocation.setOnClickListener(view -> {
            AllowPermissionUseCase.useLocation(
                    requireActivity(),
                    "定位权限",
                    "用于实现当前位置信息，需要访问您的定位权限，如若拒绝，将无法使用上述功能。",
                    "定位权限：该功能需要定位权限才可以正常运行，用于获取您当前的位置信息。",
                    "333",
                    "请开启权限",
                    (Function0<Unit>) () -> {
                        ToastUtils.showShort("已同意权限");
                        return null;
                    });
        });


        binding.tvCombo.setOnClickListener(view -> {
            List<PermissionParis> list = new ArrayList<>();
            List<String> arrayList = new ArrayList<>();
            arrayList.add(Manifest.permission.CAMERA);
            List<String> arrayList2 = new ArrayList<>();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arrayList2.add(PermissionCase.PER_READ_IMAGES);
            } else {
                arrayList2.add(PermissionCase.PER_STORAGE_WRITE);
            }
            list.add(
                    new PermissionParis(
                            "相机权限",
                            "用于实现拍摄照片、录制视频进行创作，需要访问您的相机权限，如若拒绝，将无法使用上述功能。",
                            com.ll.permission.R.drawable.icon_camera,
                            arrayList,
                            "相机权限：该功能需要相机权限才可以正常运行，用于拍摄照片或录制视频等。"
                    )
            );
            list.add(
                    new PermissionParis(
                            "相册权限",
                            "用于实现照片制作，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                            com.ll.permission.R.drawable.icon_photoalbum,
                            arrayList2,
                            "相册权限：该功能需要相册权限才可以正常运行，用于照片制作。"
                    )
            );
            AllowPermissionUseCase.requestWithPreviewDialogMulti(
                    requireActivity(),
                    list,
                    "444",
                    "请开启权限",
                    false,
                    (Function0<Unit>) () -> {
                        ToastUtils.showShort("已同意权限");
                        return null;
                    });
        });

        binding.tvPerMore.setOnClickListener(view -> {
            ToastUtils.showShort("请查阅AllowPermissionUseCase源码");
        });

        binding.tvSelectPhoto.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            pickImage(PhotoConfig.Mode.PHOTO);
        });
        binding.tvSelectVideo.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            pickImage(PhotoConfig.Mode.VIDEO);
        });

        binding.tvGetVideoList.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            loadList();
        });

        binding.tvGetVideoUrl.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            loadVideoUrl();
        });

        binding.tvGoVideoList.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            ARouter.getInstance().build(PlayVideoModuleRoute.FRAGMENT_CONTAINER_ACTIVITY)
                    .withInt("type", 1000)
                    .navigation();
        });

        binding.tvFilex.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
        });

        binding.tvGoPlayVideoList.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            //style 代表了不同风格的播放页面 目前有三个页面，传值 1 2 3
            //videoType 代表了视频播单的类型，0是老视频，1是新视频
            //playPosition 播放的位置，对应List的Index
            ARouter.getInstance().build(PlayVideoModuleRoute.ACTIVITY_VIDEO_LIST_PLAY)
                    .withString("playListId", "bilibili_BV1Qh411k75f")
                    .withInt("style", 1)
                    .withInt("videoType", 1)
                    .withInt("playPosition", 3)
                    .navigation();

        });

        binding.tvGoPlayVideoUrl.setOnClickListener(v -> {
            ARouter.getInstance().build(PlayVideoModuleRoute.ACTIVITY_VIDEO_URL_PLAY)
                    .withString("title", "测试视频")
                    .withString("url", "http://www.bestkids.net/android-static/app-static/2022-01-08/ERJ7YJQDNXBD7RMYAANHY9ENDQD3ABYL.mp4")
                    .navigation();
        });

        binding.tvGoCollection.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            ARouter.getInstance().build(PlayVideoModuleRoute.FRAGMENT_CONTAINER_ACTIVITY)
                    .withInt("type", 1001)
                    .navigation();
        });

        binding.tvGoPlayHistory.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            ARouter.getInstance().build(PlayVideoModuleRoute.FRAGMENT_CONTAINER_ACTIVITY)
                    .withInt("type", 1002)
                    .navigation();
        });

        binding.tvGoPlayVideo.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            ARouter.getInstance().build(PlayVideoModuleRoute.ACTIVITY_VIDEO_URL_PLAY)
                    .withString("title", "测试视频")
                    .withString("url", "http://www.bestkids.net/android-static/app-static/2022-01-08/ERJ7YJQDNXBD7RMYAANHY9ENDQD3ABYL.mp4")
                    .navigation();
        });

        binding.tvGoUserinfo.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            if (UserInfoUtils.getInstance().isLogin()) {
                ARouter.getInstance().build(UserModuleRoute.USER_INFO_ACTIVITY)
                        .navigation();
            } else {
                ARouter.getInstance().build(UserModuleRoute.USER_LOGIN)
                        .navigation();
            }
            if (PublicFunction.checkCanUsed(true)) {
                ToastUtils.showShort("进入了支付页面");
            }

        });

        binding.tvPermission.setOnClickListener(v -> {
//            AllowPermissionUseCase.invoke(requireActivity(), "storage", "请开启必要权限", new Function0<Unit>() {
//                @Override
//                public Unit invoke() {
//                    ToastUtils.showShort("已同意");
//                    return null;
//                }
//            });
        });

        binding.tvPayFunction.setOnClickListener(v -> {
            if (QuickClickUtils.isFastClick()) {
                return;
            }
            if (PublicFunction.checkCanUsedByPosition(1, true)) {
                ToastUtils.showShort("进入了付费功能页！");
            }
        });

        binding.tvPayVip.setOnClickListener(v -> {
            startActivity(new Intent(requireActivity(), VipTemplateActivity.class));
        });

        binding.tvIncentiveModeClickAd.setOnClickListener(v -> {
            AdUtil.clickAdAndPayWithIncentiveMode(requireActivity(), 1, 1, () -> {
                ToastUtils.showShort("使用功能");
                return Unit.INSTANCE;
            });
        });

        binding.tvIncentiveModeClickPay.setOnClickListener(v -> {
            AdUtil.clickPayOrAdWithIncentiveMode(requireActivity(), 1, () -> {
                ToastUtils.showShort("使用功能");
                return Unit.INSTANCE;
            });
        });
    }

    private void pickImage(PhotoConfig.Mode mode) {
        PhotoSelectorBuilder.builder(getActivity())
                .mode(mode)
                .isCopyToPrivate(true)
                .maxCount(9)
                .minCount(1)
//                自定义部分样式
//                .importBtnBg(R.drawable.shape_import_btn_bg)
//                .imgSelectorCover(R.drawable.shape_select_cover_bg)
//                .detailSelBtnTxtColor(Color.parseColor("#ffffff"))
//                .detailSelBtnCheckBoxBtn(R.drawable.selector_cb)
//                .detailShowImgSize(false)
//                .btnCloseRes(com.fenghuajueli.libbasecoreui.R.mipmap.base_fanhui)
                .listener(data -> LogUtils.json(data));
    }

    private void loadList() {

    }

    private void loadVideoUrl() {

    }

    @Override
    public void onResume() {
        super.onResume();
        boolean vipState = UserInfoUtils.getInstance().isVip();
        boolean adSwitch = SwitchKeyV3Helper.getAdSwitch();

        AdShowHelper.showInformationAd(
                vipState,
                adSwitch,
                requireActivity(),
                binding.flowLayout,
                "1",
                SizeUtils.px2dp(getResources().getDisplayMetrics().widthPixels),
                0f,
                null
        );
    }
}